<?php
/**
 * 订单模型
 * @author Max.Yu <max@jipu.com>
 */

namespace Shop\Model;

class OrderModel extends ShopBaseModel {

  /**
   * 自动验证规则
   * @var array
   * @author Max.Yu <max@jipu.com>
   */
  protected $_validate = array(
  );

  /**
   * 自动完成规则
   * @var array
   * @author Max.Yu <max@jipu.com>
   */
  protected $_auto = array(
  );

  /**
   * 获取订单列表
   * @param $order_sn
   */
  public function lists($map, $order = '`id` DESC', $field = true, $limit = '10'){
    $result = $this->field($field)->where($map)->order($order)->limit($limit)->select();
    return $result;
  }

  /**
   * 获取订单信息
   * @author buddha <[email address]>
   * @param  [type] $order_sn 订单号
   * @return [type]        [description]
   */
  public function getOrderInfo($map, $field = true){
    $result = $this->field($field)->where($map)->find();
    return $result;
  }



  /**
   * 根据order_sn 获取 order_id
   * @param $order_sn
   */
  public function getIdBySn($order_sn = null){
    if(empty($order_sn)){
      return false;
    }

    $order_id = $this->getFieldByOrderSn($order_sn, 'id');

    if($order_id){
      return $order_id;
    }else{
      return false;
    }
  }
  
  /**
   * 获取灵通打单所需数据
   * @param array $ids 描述信息
   */
  public function getBestMartData($ids = array()){
    if(empty($ids)){
      return false;
    }
    $data = array();
    $orders = $this->field('id, order_sn, total_quantity, payment_id,create_time')->where(array('id' => array('IN', $ids)))->select();
    foreach($orders as $v){
      $ship  = M('OrderShip')->getByPaymentId($v['payment_id']);
      $area  = explode(' ', $ship['ship_area']);
      //$goods = M('Order_item')->where('order_id='.$v['id'])->getField('name', true);
      $goods = M('Order_item')->where('order_id='.$v['id'])->field('name,number')->select();
      $goodsname = '';
      $numbers = '';
      foreach ($goods as $key=>$val){
          $goodsname = $val['name'].',';
          $numbers = $val['number'].',';
      }
      $goodsname = trim($goodsname,',' );
      $numbers = trim($numbers,',');
      $data[] = array(
        $v['order_sn'], $ship['ship_uname'], $ship['ship_mobile'],
        $area[0], $area[1], $area[2], $ship['ship_address'], $goodsname,$numbers , $v['total_quantity'], ($ship['ship_phone'] ?: '') ,date('Ymd H:i:s' , $v['create_time'])
      );
    }
    return $data;
  }

  /**
   * 订单状态更新
   * @param null $data
   * @return bool
   */
  public function updateField($data = null){
      /* 获取数据对象 */
      $data = $this->create($data) ? $this->create($data) : I('get.');
      if(empty($data)){
          return false;
      }
      if($data['id']){
          $model = M('StoreOrder');
          //查询原来金额
          $storeOrder = $model->where('id='.$data['id'])->field('total_amount,order_sn,store_ids AS store_id')->find(); 
          $order = M('Order')->where('order_sn='.$storeOrder['order_sn'])->field('total_amount,store_other,payment_id')->find();
          $payment = M('Payment')->find($order['payment_id']);
          $arr = array(
              'card_amount'    => 0,
              'score_amount'   => 0,
              'finance_amount' => 0
            );
          if ($payment['is_use_card'] > 0 ) {
            $arr['card_amount'] = $payment['card_amount'];
          }
          if ($payment['score_amount'] > 0) {
            $arr['score_amount'] = $payment['score_amount'];
          }
          if ($payment['is_use_finance'] > 0) {
            $arr['finance_amount'] = $payment['finance_amount'];
          }
          //开启事务
          $model->startTrans();
          //新的
          $cha_amount = $storeOrder['total_amount'] - $data['total_amount'];
          $new_amount = $order['total_amount'] - $cha_amount;
          $new_order_amount = ($new_amount < 0) ? 0 : $new_amount;

          $store_other = unserialize($order['store_other']);
          $store_other['store_amount'][$storeOrder['store_id']] = $data['total_amount'];
          foreach ($store_other['store_amount'] as $key => $value) {
             $new_store_order_amount += $value;
          }

          $new_store_other = serialize($store_other);
          $cdata = array(
              //'total_amount' => $new_order_amount,//待支付金额
              'store_other'  => $new_store_other
            );
          // 从大到小 排序
          if ( ($arr['card_amount'] == $arr['score_amount']) ||($arr['card_amount'] == $arr['finance_amount']) || $arr['score_amount'] == $arr['finance_amount'] ) {
              if ( ($arr['card_amount'] == $arr['score_amount']) && ($arr['card_amount'] == $arr['finance_amount']) ) {
                 $arr_sort = array(
                    'score_amount'   => $arr['score_amount'],
                    'finance_amount' => $arr['finance_amount'],
                    'card_amount'    => $arr['card_amount']
                );
              }else{
                  $num_arr = array(
                      'score_amount' => $arr['score_amount'],
                      'finance_amount'=> $arr['finance_amount'],
                      'card_amount' => $arr['card_amount']
                    );
                  $max_num = ($arr['finance_amount'] >= $arr['card_amount']) ? (($arr['finance_amount'] >= $arr['score_amount'] ) ? $arr['finance_amount'] : $arr['score_amount']) : (($arr['card_amount'] >= $arr['score_amount']) ? $arr['card_amount'] : $arr['score_amount']);
                  $num_values = array_values($num_arr);
                  $num_keys = array_keys($num_arr);
                  foreach ($num_values as $key => $value) {
                    if ($value == $max_num) {
                      $new_key = $num_keys[$key];
                    }
                  }
                  switch ($new_key) {
                    case 'finance_amount':
                      if ($arr['score_amount'] == $arr['card_amount']) {
                          $arr_sort = array(
                            'finance_amount' => $arr['finance_amount'],
                            'score_amount'   => $arr['score_amount'],
                            'card_amount'    => $arr['card_amount']
                          );
                      }else{
                          if ($arr['score_amount'] == $arr['finance_amount']) {
                              $arr_sort = array(
                                'finance_amount' => $arr['finance_amount'],
                                'score_amount'   => $arr['score_amount'],
                                'card_amount'    => $arr['card_amount']
                              );
                          }else{
                              $arr_sort = array(
                                'finance_amount' => $arr['finance_amount'],
                                'card_amount'    => $arr['card_amount'],
                                'score_amount'   => $arr['score_amount']
                              );
                          }     
                      } 
                      break;
                    case 'card_amount':
                      if ($arr['score_amount'] == $arr['finance_amount']) {
                          $arr_sort = array(
                            'card_amount'    => $arr['card_amount'],
                            'score_amount'   => $arr['score_amount'],
                            'finance_amount' => $arr['finance_amount'] 
                          );
                      }else{
                          if ($arr['score_amount'] == $arr['card_amount']) {
                              $arr_sort = array(
                                'card_amount'    => $arr['card_amount'],
                                'score_amount'   => $arr['score_amount'],
                                'finance_amount' => $arr['finance_amount']
                              );
                          }else{
                              $arr_sort = array(
                                'card_amount'    => $arr['card_amount'],
                                'finance_amount' => $arr['finance_amount'],
                                'score_amount'   => $arr['score_amount']
                              );
                          }     
                      } 
                      break;
                    default:
                      if ($arr['card_amount'] == $arr['finance_amount']) {
                          $arr_sort = array(
                            'score_amount'   => $arr['score_amount'],
                            'finance_amount' => $arr['finance_amount'],
                            'card_amount'    => $arr['card_amount'] 
                          );
                      }else{
                          if ($arr['score_amount'] == $arr['card_amount']) {
                              $arr_sort = array(
                                'score_amount'   => $arr['score_amount'],
                                'card_amount'    => $arr['card_amount'],
                                'finance_amount' => $arr['finance_amount']
                              );
                          }else{
                              $arr_sort = array(
                                'score_amount'   => $arr['score_amount'],
                                'finance_amount' => $arr['finance_amount'],
                                'card_amount'    => $arr['card_amount']
                              );
                          }     
                      } 
                      break;
                  }
              }
          }else{
              $arr_sort = $this->sort_with_keyName($arr);
          }
          $arr_values = array_values($arr_sort);
          $arr_keys = array_keys($arr_sort);

          $other_amount = $arr['card_amount'] + $arr['score_amount'] + $arr['finance_amount'];
          //修改后 订单总金额
          foreach ($store_other['store_amount'] as $key => $value) {
            $max_amount += $value;
          }
          //添加判断
          $payment_data = array();
          if ($max_amount < $other_amount) {           
            if ($max_amount <= $arr_values[0]) {
                $key = $arr_keys[0];
                switch ($key) {
                  case 'card_amount':
                      $payment_data = array(
                          'card_amount'    => $max_amount,
                          'is_use_finance' => 0,
                          'finance_amount' => 0,
                          'use_score'      => 0,
                          'score_amount'   => 0
                        );
                    break;
                   case 'score_amount':
                     $use_score = $max_amount*C('SCORE_EXCHANGE_NUMBER');
                     $payment_data = array(
                          'use_score'      => $use_score,
                          'score_amount'   => $max_amount,
                          'is_use_finance' => 0,
                          'finance_amount' => 0,
                          'is_use_card'    => 0,
                          'card_id'        => 0,
                          'card_amount'    => 0
                        );
                    break;
                  default:
                     $payment_data = array(
                          'finance_amount' => $max_amount,
                          'use_score'      => 0,
                          'score_amount'   => 0,
                          'is_use_card'    => 0,
                          'card_id'        => 0,
                          'card_amount'    => 0
                        );
                    break;
                }
            }elseif($max_amount <= ($arr_values[0] + $arr_values[1]) && $max_amount > $arr_values[0]){
              $key = $arr_keys[2];
                $diff = $arr_values[0] + $arr_values[1] - $max_amount;
                switch ($key) {
                  case 'card_amount':
                      $payment_data = array(
                          'is_use_card'    => 0,
                          'card_id'        => 0,
                          'card_amount'    => 0
                        );
                      if ($arr_keys[0] == 'finance_amount') {
                        $payment_data['score_amount'] = $arr['score_amount'] - $diff;
                        $payment_data['use_score'] = $payment_data['score_amount']*C('SCORE_EXCHANGE_NUMBER');
                      }
                      if ($arr_keys[0] == 'score_amount') {
                        $payment_data['finance_amount'] = $arr['finance_amount'] - $diff;
                      }
                    break;
                   case 'score_amount':
                     $payment_data = array(
                          'use_score'      => 0,
                          'score_amount'   => 0,
                        );
                      if ($arr_keys[0] == 'finance_amount') {
                        $payment_data['card_amount'] = $arr['card_amount'] - $diff;
                      }
                      if ($arr_keys[0] == 'card_amount') {
                        $payment_data['finance_amount'] = $arr['finance_amount'] - $diff;
                      }
                    break;
                  default:
                     $payment_data = array(
                          'is_use_finance' => 0,
                          'finance_amount' => 0
                        );
                      if ($arr_keys[0] == 'score_amount') {
                        $payment_data['card_amount'] = $arr['card_amount'] - $diff;
                      }
                      if ($arr_keys[0] == 'card_amount') {
                        $payment_data['score_amount'] = $arr['score_amount'] - $diff;
                        $payment_data['use_score'] = $payment_data['score_amount']*C('SCORE_EXCHANGE_NUMBER');
                      }
                    break;
                }
            }else{
              $keys = $arr_keys[2];
              switch ($keys) {
                case 'card_amount':
                    $payment_data['card_amount'] = $arr['card_amount'] - ($other_amount - $max_amount);
                  break;
                 case 'score_amount':
                  $score_amount = $arr['score_amount'] - ($other_amount - $max_amount);
                  $use_score = $score_amount * C('SCORE_EXCHANGE_NUMBER');
                  $payment_data = array(
                      'score_amount' => $score_amount,
                      'use_score'    => $use_score
                      );
                  break;
                default:
                  $payment_data['finance_amount'] = $arr['finance_amount'] - ($other_amount - $max_amount);
                  break;
              }
            }
            $result = M('Payment')->where('id='.$order['payment_id'])->save($payment_data);
          }else{
            $result = true;
          }
          //再次修改平台订单、商户订单余额
          if ( ($payment_data['finance_amount'] > 0) && ($arr['finance_amount'] != $payment_data['finance_amount']) ) {
              $cdata['finance_amount'] = $payment_data['finance_amount'];
              $data['finance_amount'] =  sprintf("%.2f",$payment_data['finance_amount'] * $data['total_amount'] / $max_amount);
          }
          //再次查询payment表 重定义total_amount
          $new_payment = M('Payment')->find($order['payment_id']);
          $new_total_order_amount = $new_payment['finance_amount'] + $new_payment['card_amount'] + $new_payment['score_amount'];
          $cdata['total_amount'] = sprintf('%.2f',$new_store_order_amount - $new_total_order_amount);
          //dump($cdata);exit;
          $res = M('StoreOrder')->where(array('id'=>$data['id']))->save($data); 
          $re = M('Order')->where('order_sn='.$storeOrder['order_sn'])->save($cdata);
          if ($result && $res && $re) {
             $model->commit();
             return $res;
          }else{
             $model->rollback();
             return false;
          }     
      }
  }

  private function sort_with_keyName($arr,$orderby='desc'){
    //在内存的另一处 $a 复制内容与 $arr 一样的数组
        foreach($arr as $key => $value) 
        $a[$key]=$value;
        if($orderby== 'asc'){//对数组 $arr 进行排序
            asort($arr);
        }else{
            arsort($arr);
        }                         
    /*创建一个以原始数组的键名为元素值 (键值) 的
     *数组 $b, 其元素 (键值) 顺序，与排好序的数组 $arr 一致。
    */
        $index=0;
        foreach ($arr as $keys => $values) //按排序后数组的顺序
        foreach($a as $key => $value) //在备份数组中寻找键值
        if ($values==$value)//如果找到键值
        $b[$index++]=$key; // 则将数组 $b 的元素值，设置成备份数组 $a 的键名 
    //返回用数组 $b 的键值作为键名,数组 $arr 的键值作为键值,所组成的数组 
        return array_combine($b, $arr);
    }
}